package com.bwf.dao;

import com.bwf.pojo.Student;
import com.bwf.util.DBUtil;
import com.bwf.util.DateUtil;

import java.sql.*;
import java.util.ArrayList;

public class StudentDaoImpl implements StudentDao {
    @Override
    public ArrayList<Student> query() {
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        try {
            connection = DBUtil.getConn();
            preparedStatement = connection.prepareStatement("select * from t_student");
            resultSet = preparedStatement.executeQuery();
            ArrayList<Student> list = new ArrayList<>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date birthday = resultSet.getDate("birthday");
                int salary = resultSet.getInt("salary");
                Date createTime = resultSet.getDate("create_time");
                Date updateTime = resultSet.getDate("update_time");
                int classId = resultSet.getInt("class_id");
                Student student = new Student(id, name, sex, DateUtil.DateConvert(birthday), salary, DateUtil.DateConvert(createTime), DateUtil.DateConvert(updateTime), classId);
                list.add(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException("查询学生出错");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }
        return null;
    }
}
